package com.ash.servlet;


import com.ash.dao.dao.imp.DaoImpl;
import com.ash.dao.domain.User;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;

import java.util.List;
import java.util.Map;


/**
 * @encoding : UTF-8
 * @Time : 2020/12/9 14:35
 * @Author : Chen Chao
 * @File : TestLogin.${PACKAGE_NAME}.${NAME}.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        res.setContentType("text/html;charset=UTF-8");
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
            DaoImpl<User> userDao = new DaoImpl<>(User.class,"id");
            userDao.add(user);
            System.out.println("注册成功！");
            res.setHeader("refresh","5;/index.html");
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws  IOException {
        res.setContentType("text/html;charset=UTF-8");


        /*判断验证码*/
        String code = req.getParameter("code");
        String code1 = (String) this.getServletContext().getAttribute("code");
        if(!code.equalsIgnoreCase(code1)){
            System.out.println("验证码不正确！");
            res.sendRedirect("/index.html");
        }
        /*判断用户名与密码*/
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        DaoImpl<User> userDao = new DaoImpl<>(User.class,"id");
        List<User> select = userDao.select(user);
        if(select==null){
            System.out.println("用户名或密码不正确！");
            res.sendRedirect("/index.html");
        }
        res.sendRedirect("/success.html");
    }

}